<template>
  <div class="repair-type-container">
    <div class="app-container">
      <el-card class="box-card">
        <!-- 页头 -->
        <div
          slot="header"
          class="clearfix"
        >
          <span>报修类型管理</span>

          <div class="box-add">
            <el-button
              type="primary"
              @click="addRepairerTypeFn()"
            >添加大报修类型</el-button>
          </div>
        </div>

        <!-- 列表 -->
        <el-tree
          class="departments-tree"
          :data="treeData"
          :props="{label: 'name'}"
          highlight-current
          accordion
          :indent='40'
        >
          <template #default="{ data }">
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
              style="width: 100%"
            >
              <!-- 部门名字 -->
              <el-col :span="20">
                <span>{{ data.name }}</span>
              </el-col>
              <!-- 功能操作区域 -->
              <el-col :span='4'>
                <el-popover
                  placement="left"
                  max-width="80"
                  trigger="hover"
                  :close-delay='0'
                >
                  <el-popconfirm
                    title="确定删除该报修类型吗？如有进行中的报修单报属于该修类型或该类型有子类型则无法删除！"
                    @confirm="rowDeleteFn(data)"
                  >
                    <el-button
                      type="danger"
                      circle
                      icon="el-icon-delete"
                      size="mini"
                      slot="reference"
                    ></el-button>
                  </el-popconfirm>
                  <el-button
                    circle
                    size="mini"
                    icon="el-icon-search"
                    @click="rowInfoFn(data)"
                  ></el-button>
                  <el-button
                    type="primary"
                    circle
                    icon="el-icon-edit"
                    size="mini"
                    @click="rowUpdateFn(data)"
                  ></el-button>
                  <el-button
                    type="success"
                    circle
                    icon="el-icon-plus"
                    size="mini"
                    @click="addRepairerTypeFn(data)"
                  ></el-button>
                  <el-button
                    slot="reference"
                    size="mini"
                  >操作</el-button>
                </el-popover>
              </el-col>
            </el-row>
          </template>
        </el-tree>

        <el-dialog
          title="报修类型信息"
          :visible.sync="dialogInfoVisible"
          @close="dialogCloseFn()"
          :show-close='false'
          custom-class='dialog-info-35'
        >
          <el-descriptions
            border
            :column='1'
            labelClassName="width-120"
          >
            <el-descriptions-item label="id号">{{repairTypeInfo.id}}</el-descriptions-item>
            <el-descriptions-item label="名称">{{repairTypeInfo.name}}</el-descriptions-item>
            <el-descriptions-item label="父类型">{{originObject[[repairTypeInfo.pid]]?.name}}</el-descriptions-item>
            <el-descriptions-item label="维修人员类型">{{typeObject[repairTypeInfo.r_type_id]?.label}}</el-descriptions-item>
            <el-descriptions-item label="添加者工号">{{repairTypeInfo.job_number}}</el-descriptions-item>
          </el-descriptions>
        </el-dialog>

        <el-dialog
          :title="isAdd ? '添加报修类型':'修改报修类型信息'"
          :visible.sync="dialogUpdateVisible"
          @close="dialogCloseFn()"
          :close-on-click-modal='false'
          :show-close='false'
          custom-class='dialog-35'
        >
          <el-form
            :model="repairTypeInfo"
            status-icon
            :rules="repairTypeRules"
            ref="repairTypeInfo"
            label-width="120px"
          >
            <el-form-item
              label="名称"
              prop="name"
            >
              <el-input
                v-model.trim="repairTypeInfo.name"
                @keyup.enter.native="updateSubmitFn()"
              ></el-input>
            </el-form-item>
            <el-form-item
              v-if="!repairTypeInfo.pid"
              label="维修人员类型"
              prop="r_type_id"
            >
              <el-select
                filterable
                clearable
                v-model="repairTypeInfo.r_type_id"
                placeholder="请选择维修人员类型"
              >
                <el-option
                  v-for="item in typeObject"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="center">
              <el-button @click="dialogUpdateVisible = false">取消</el-button>
              <el-button
                type="primary"
                @click="updateSubmitFn()"
              >{{isAdd ? '添加':'修改'}}</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-card>

    </div>
  </div>
</template>

<script>
import { transTree } from '@/utils'
import {
  addRepairTypeAPI,
  deleteRepairTypeAPI,
  getRepairerTypeListAPI,
  getRepairTypeListAPI,
  updateRepairTypeAPI
} from '@/api'

export default {
  name: 'repairType',
  data () {
    // 判断是有对应的维修人员类型
    const validTypeId = (rule, value, callback) => {
      if (!this.repairTypeInfo.pid && !value) {
        callback(new Error('维修人员类型不能为空'))
      }
      value &&
        (Object.keys(this.typeObject).includes(value)
          ? callback()
          : callback(new Error('维修人员类型不存在')))
      callback()
    }
    // 同级报修类型禁止重复名称
    const validName = (rule, value, callback) => {
      // 查找同级的分类
      let existNameList

      if (this.isAdd) {
        existNameList = Object.values(this.originObject)
          .filter((item) => item.pid === this.repairTypeInfo.pid)
          .map((item) => item.name)
      } else {
        existNameList = Object.values(this.originObject)
          .filter(
            (item) =>
              item.pid === this.repairTypeInfo.pid &&
              item.id !== this.repairTypeInfo.id
          )
          .map((item) => item.name)
      }

      // 判断最新输入的部门名称是否存在
      existNameList.includes(value)
        ? callback(new Error(value + '已经被占用了'))
        : callback()
    }
    return {
      state: 0,
      repairTypeList: [], // 报修类型列表
      // 树形控件数据
      treeData: [], // 定义结构显示
      originObject: {}, // 用于弹窗内-校验部门code和name是否重复数据数组
      dialogInfoVisible: false, // 信息展示 dialog 控制
      dialogUpdateVisible: false, // 修改信息 dialog 控制
      repairTypeInfo: {}, // dialog 数据
      repairTypeRules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 15,
            type: 'string',
            message: '名称要求1-15个数字',
            trigger: 'blur'
          },
          { validator: validName, trigger: 'blur' }
        ],
        r_type_id: [{ validator: validTypeId, trigger: 'blur' }],
        pid: [
          {
            min: 32,
            max: 32,
            type: 'string',
            message: 'pid要求32个数字',
            trigger: 'blur'
          }
        ]
      }, // dialog 数据验证
      isAdd: false, // 是否是添加操作
      typeObject: {} // 维修人员类型数据
    }
  },
  created () {
    this.getRepairTypeListFn()
    this.getRepairerTypeFn()
  },
  methods: {
    // 点击添加按钮
    addRepairerTypeFn (d) {
      this.repairTypeInfo.pid = d?.id ? d.id : ''
      this.isAdd = true
      this.dialogUpdateVisible = true
    },
    // 点击查看 -> 展示数据详情
    rowInfoFn (d) {
      this.repairTypeInfo = d
      this.dialogInfoVisible = true
    },
    // 点击修改 -> 展示数据 -> 修改
    rowUpdateFn (d) {
      this.state = d.pid ? 0 : 1
      this.repairTypeInfo = { ...d }
      this.isAdd = false
      this.dialogUpdateVisible = true
    },
    // 点击删除 -> 删除该年级
    async rowDeleteFn (d) {
      try {
        const { success, code } = await deleteRepairTypeAPI(d.id)
        if (success && code === 10000) {
          success && this.getRepairTypeListFn()
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 获取报修类型列表 -> 发送请求
    async getRepairTypeListFn () {
      try {
        const { success, code, data } = await getRepairTypeListAPI()
        if (success && code === 10000) {
          this.repairTypeList = data
          // 格式化需要传递给子组件的数据
          data.forEach((item) => {
            this.$set(this.originObject, item.id, {
              id: item.id,
              name: item.name,
              pid: item.pid // 下面使用
            })
          })
          this.treeData = transTree(data, '')
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 获取维修人员类型 -> 发送请求
    async getRepairerTypeFn () {
      try {
        const { success, code, data } = await getRepairerTypeListAPI({
          page: 1
        })
        if (success && code === 10000) {
          data.row.forEach((item) => {
            this.$set(this.typeObject, item.id, {
              value: item.id,
              label: item.name
            })
          })
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // dialog 关闭
    dialogCloseFn () {
      this.repairTypeInfo = this.$options.data().repairTypeInfo
      this.$refs.repairTypeInfo?.resetFields()
    },
    // dialog 点击添加/修改 -> 发起请求
    async updateSubmitFn () {
      this.$refs.repairTypeInfo.validate(async (valid) => {
        if (valid) {
          try {
            let success, code
            if (this.isAdd) {
              ; ({ success, code } = await addRepairTypeAPI(this.repairTypeInfo))
            } else {
              ; ({ success, code } = await updateRepairTypeAPI(
                this.repairTypeInfo
              ))
            }

            if (success && code === 10000) {
              success && this.getRepairTypeListFn()
              this.dialogUpdateVisible = false
            }
          } catch (err) {
            return console.dir(err)
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.box-card {
  padding: 10px 30px;
}

.clearfix {
  display: flex;
}

.tab-pane {
  padding: 20px 80px;

  .company {
    margin-left: 12px;
    font-weight: bold;
    font-size: 14px;
  }

  .department-header {
    height: 50px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ccc;
  }
}
</style>
